import { _decorator, Component } from 'cc';
const { ccclass, property } = _decorator;
import * as fgui from "fairygui-cc";
import PlayerEntity from "../entity/PlayerEntity"
import { GameController } from '../manager/GameController';
import PlayerBoxEntity from '../entity/PlayerBoxEntity';
import { AudioManager } from '../manager/AudioManager';

import { RandomSelector } from '../utils/RandomSelector';

export default class PlayerCtrl {

    public playersBox: fgui.GComponent

    private _node: fgui.GComponent = null;

    private _playerEntityList: Array<PlayerEntity> = []
    private _playerBoxEntityList: Array<PlayerBoxEntity> = []

    private _playersListContainer: fgui.GComponent;
    private _player: PlayerEntity = null;
    private _playerListShow: fgui.Controller = null;

    private _randomSelector: RandomSelector = null;

    public refreshToastHandle: () => void = null;
    public refreshing: boolean = false;

    private boxX = 0;
    private boxY = 0;

    constructor(node: fgui.GComponent, playersBox: fgui.GComponent, playerList: fgui.GComponent, playerListShow: fgui.Controller) {
        this._node = node;
        this.playersBox = playersBox;

        this.boxX = this.playersBox.x;
        this.boxY = this.playersBox.y;
        console.log(playersBox)

        this._playersListContainer = playerList.getChild('n1').asCom;
        this._playerListShow = playerListShow;
        this.initPlayerEntityList()
    }

    initPlayerBox() {
        if (this.playersBox == null) {
            console.log('!! add new playerBox !!')
            const newbox = fgui.UIPackage.createObject("GameBoom", "zhan_home").asCom
            this._node.addChildAt(newbox, 2)
            newbox.x = this.boxX;
            newbox.y = this.boxY;
            this.playersBox = newbox;

            this.initPlayerEntityList();
        }
    }

    initPlayerEntityList() {
        this._playerEntityList = this._playerEntityList || [];
        const PLAYER_BASE_NUM = 37;
        const EXPECTED_PLAYERS = 10;

        for (let order = 0; order < EXPECTED_PLAYERS; order++) {
            // 动态生成节点名称
            const targetNodeName = `n${PLAYER_BASE_NUM + order}`;
            // 安全获取节点（带类型校验）
            const uiComponent = this.getValidPlayerComponent(targetNodeName, this.playersBox);
            if (!uiComponent) continue;
            this.createAndStoreEntity(uiComponent, order);
        }
    }

    // 分离实体创建逻辑
    private createAndStoreEntity(uiComponent, order) {
        try {
            const entity = new PlayerEntity(
                uiComponent,
                order
            );
            this._playerEntityList.push(entity);
        } catch (e) {
            console.error(`Failed to create player entity ${order}:`, e);
        }
    }

    creatorRandomSelectorAndStart() {

        this.initPlayerBox()

        if (this._randomSelector) {
            this._randomSelector.destroy();
            this._randomSelector = null;
        }
        this._randomSelector = new RandomSelector(
            this._playerEntityList,
            () => this.allEntityTransty(),
            400,
            2400,
            // 1500
        );

        // 开始执行
        this._randomSelector.start();
    }

    allEntityTransty() {
        this.refreshing = true;

        [...this._playerEntityList].slice(0).forEach(entity => {
            setTimeout(() => {
                entity.demoTransfer()
            }, 1000);
            if (this.refreshToastHandle) {
                this.refreshToastHandle();
            }
        })
        setTimeout(() => {
            this.refreshing = false;
            this.creatorRandomSelectorAndStart()
        }, 2010);
    }

    initPlayerBoxList(nums: number) {
        this._playerBoxEntityList = this._playerBoxEntityList || [];
        let tempHeight: number = 0
        for (let index = 0; index < nums; index++) {
            const uiComponent = fgui.UIPackage.createObject("GameBoom", "progress").asCom
            if (!uiComponent) continue;
            this._playersListContainer.addChild(uiComponent)
            uiComponent.x = (this._playersListContainer.width - uiComponent.width) / 2
            uiComponent.y = (uiComponent.height + 5) * index + 5
            tempHeight += uiComponent.height + 5;
            this.createAndStoreBoxEntity(uiComponent);
        }

        this._playersListContainer.x = 0
        this._playersListContainer.y = 52

        this._playersListContainer.height = tempHeight + 24;
    }

    // 分离组件获取逻辑
    private getValidPlayerComponent(nodeName, parentNode) {
        const node = parentNode.getChild(nodeName);
        // 可选调试输出
        if (!node?.asCom) {
            console.warn(`Player node ${nodeName} not found or invalid type`);
            return null;
        }
        return node.asCom;
    }

    // 分离实体创建逻辑
    private createAndStoreBoxEntity(uiComponent) {
        try {
            const entity = new PlayerBoxEntity(
                uiComponent
            );
            this._playerBoxEntityList.push(entity);
        } catch (e) {
            console.error(`Failed to create player entity:`, e);
        }
    }

    public gameReady() {

        // this._player = this._playerEntityList[0]
        // this._player.display(true);

        // if (this._player) {
        //     this._player.playerReady();
        // }

        // this._playerEntityList.forEach((entity, idx) => {
        //     entity.display(idx == 0);
        //     entity.playerReady();
        // })
    }

    public gameStart() {
        this._playerListShow.setSelectedIndex(1)
        const count = GameController.Instance.playersCount;
        [...this._playerEntityList].slice(0, count).forEach(entity => {
            entity.playerGameTransfer()
        })
    }

    public gameReConnect() {

        this._playerListShow.setSelectedIndex(1)
        const count = GameController.Instance.playersCount;
        [...this._playerEntityList].slice(0, count).forEach(entity => {
            entity.playerTrunOn()
        })
    }

    public monsterBoom() {
        let resultArray = null;
        try {
            resultArray = GameController.Instance.gameResultData.resultArray;
        } catch (error) {
            console.log(error)
        }

        if (resultArray == null) return;

        const displayEntityArray = [...this._playerEntityList].slice(0, resultArray.length)
        resultArray.forEach(item => {
            const failEntity = displayEntityArray.find(entity => item.memberId == entity.memberId && item.result === false)
            if (failEntity) {
                failEntity.updateBoom();
            }
        })
    }

    //游戏准备队列更新
    public gameUpdateReadyPlayersQueue() {

        this.initPlayerBox()

        this.cancleRandomSelector();
        this._playerEntityList.forEach((entity, idx) => {
            entity.display(idx == 0);
        })
        const count = GameController.Instance.playersCount
        if (count > 0) {
            [...this._playerEntityList].slice(0, count).forEach(entity => {
                entity.playerReady()
            })
        }
    }

    //更新在场玩家数据
    public updatePlayerInfo(playerInfoArray: Array<playerInfo>) {

        this.initPlayerBox()

        const displayEntityArray = [...this._playerEntityList].slice(playerInfoArray.length)
        displayEntityArray.forEach(player => {
            player.display(false)
        })

        if (this._playerBoxEntityList.length == 0) {
            if (this._playerListShow.selectedIndex === 0) {
                this._playerListShow.setSelectedIndex(1)
            }

            this.initPlayerBoxList(playerInfoArray.length)

            playerInfoArray.forEach((playerInfo: playerInfo, Index) => {
                const playerEntity = this._playerEntityList[Index]
                if (playerInfo.memberId === GameController.Instance.memberId) {
                    this._player = playerEntity;
                    this._player.isSelf = true;
                }
                else {
                    playerEntity.isSelf = false;
                }
                playerEntity.updateInfo(playerInfo)
            })
        }
        else {
            AudioManager.Instance.playEffectWithName('energy')
            playerInfoArray.forEach((playerInfo: playerInfo, Index) => {
                const playerEntity = this._playerEntityList[Index]
                if (playerInfo.memberId === GameController.Instance.memberId) {
                    this._player = playerEntity;
                    this._player.isSelf = true;
                }
                else {
                    playerEntity.isSelf = false;
                }
                playerEntity.updateInfo(playerInfo)
            })
        }

        this.updatePlayerBoxInfo(playerInfoArray)
    }

    public updatePlayerBoxInfo(playerInfoArray: Array<playerInfo>) {
        // 排序逻辑
        const sortedPlayerInfoArray = [...playerInfoArray].sort((a: playerInfo, b: playerInfo) => {
            const aExceeds = a.shield > 30;
            const bExceeds = b.shield > 30;
            // 情况 1：一个超过，一个未超过
            if (aExceeds !== bExceeds) {
                return aExceeds ? 1 : -1; // 超过的排在后面
            }
            // 情况 2：同为超过或同为未超过时，按 shield 降序排列
            else {
                return b.shield - a.shield; // 大值在前
            }
        });

        sortedPlayerInfoArray.forEach((playerInfo: playerInfo, index) => {
            let boxEntity = this._playerBoxEntityList[index];
            boxEntity.updatePlayerInfo(playerInfo)
        })
    }

    public updateSelfEnergy() {
        if (this._player) {
            this._player.updateEnergy(GameController.Instance.currentEnergy);
        }
    }

    private cancleRandomSelector() {
        if (this._randomSelector) {
            this._randomSelector.destroy();
            this._randomSelector = null;
        }
    }

    public reset() {
        if (this._player) {
            this._player.isSelf = false;
            this._player = null;
        }

        if (this._playerBoxEntityList.length > 0) {

            this._playerBoxEntityList.forEach(box => {
                box.destroy();
            })
            this._playerBoxEntityList = []
            this._playerListShow.setSelectedIndex(0)
        }

        this._playerEntityList.forEach((player, index) => {
            player.resetInfo()
        })

        if (this.playersBox != null) {
            this.playersBox.removeFromParent();
            this._playerEntityList = [];
            this.playersBox = null
        }

        this.cancleRandomSelector();
    }
}